package com.primary.common;

import com.sun.management.OperatingSystemMXBean;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

/**
 * @author Shen Jianhui
 * @date 2024/03/02 21:54 Saturday
 * @description
 */
public class SystemInfo {
    public static void getLocalHostInfos() throws UnknownHostException, InterruptedException {
        InetAddress localhost = InetAddress.getLocalHost();
        String ipAddress = localhost.getHostAddress();
        String hostName = localhost.getHostName();
        Properties props = System.getProperties();
        String osName = props.getProperty("os.name");
        String osVersion = props.getProperty("os.version");
        OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        String totalPhysicalMemorySize = operatingSystemMXBean.getTotalMemorySize() / (1024 * 1024)+" MB"; // 总物理内存大小（字节）
        long availableProcessors = operatingSystemMXBean.getAvailableProcessors(); // CPU核心数
        System.out.println("本机IP地址: " + ipAddress);
        System.out.println("本机主机名: " + hostName);
        System.out.println("操作系统名称: " + osName);
        System.out.println("操作系统版本: " + osVersion);
        System.out.println("CPU核心数: " + availableProcessors);
        System.out.println("总物理内存大小: " + totalPhysicalMemorySize); // 转换为MB
        for(int i=0;i<=600;i++){
            String systemCpuLoad = String.format("%.2f%%", operatingSystemMXBean.getCpuLoad() *100); // 系统CPU负载
            System.out.println("当前CPU利用率: " +systemCpuLoad);
            Thread.sleep(1000);
        }
    }

    public static void main(String[] args) throws UnknownHostException, InterruptedException {
        getLocalHostInfos();
    }
}
